package net;

import db.DBConnection;
import log.Logger;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 * User: SLeeP
 * Date: 25.02.12
 * Time: 4:38
 */
public class Connection {
    private final static int PORT = 14000;
    private final static int CHUNK_SIZE = 10;
    private final static String ACTION_TYPE = "action_type";

    private ServerSocket serverSocket;
    private DBConnection dbConnection;
    
    //private Socket socket;

    public Connection() throws Exception {
        this(PORT);
    }

    public Connection(int port) throws Exception{
        serverSocket = new ServerSocket(port);
        dbConnection = new DBConnection();
    }

    public void run() throws IOException {
        int i = 0;
        while (true) {
            Socket socket = serverSocket.accept();
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String query = br.readLine();
            Logger.write(query, Logger.Mode.ACTION);

            if (query.contains("stop")) {
                send(socket, "stopped");
                break;
            } else {
                if (query.contains("favicon.ico")) {
                    continue;
                }
            }
            ArrayList<String> res = parseRequest(query);
            send(socket, getResponse(res));
            socket.close();
        }
    }
    
    public ArrayList<String> parseRequest(String request) {
        try {
            String params = request.split(" ")[1].split("[?]")[1];
            String[] args = params.split("[&]");
            ArrayList<String> result = new ArrayList<String>();
            for (String str : args) {
                String[] s = str.split("=");
                result.add(s[0]);
                result.add(s[1]);
            }
            return result;
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    }

    public String getResponse(ArrayList<String> params) {
        if (params == null) {
            return "null";
        }
        int pos = params.indexOf(ACTION_TYPE);
        
        if (pos == -1) {
            return "ERROR IN REQUEST FORMAT";
        }

        String actionType = params.get(pos + 1);
        if (actionType.equalsIgnoreCase(DBConnection.Operation.LOGIN_OPERATION.toString())) {
            String login = params.get(params.indexOf("login") + 1);
            String password = params.get(params.indexOf("password") + 1);
            if (dbConnection.login(login, password)!= 1) {
                return "LOGIN SUCCESSFUL";
            } else {
                return "LOGIN FAILED";
            }
        } else if (actionType.equalsIgnoreCase(DBConnection.Operation.LOGOUT.toString())) {
            if (dbConnection.logout(1, "1")) {
                return "LOGOUT SUCCESSFUL";
            } else {
                return "LOGOUT FAILED";
            }
        } else {
            return "UNKNOWN OPERATION";
        }
        
    }

    public void send(Socket socket, String message) {
        try {
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            pw.write(message);
            pw.flush();
            pw.close();
        } catch (IOException e) {
            Logger.write("Lost connection to the client when sending!!!", Logger.Mode.ERROR);
            e.printStackTrace();
        }
    }
}
